﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TVShows.Data;
using TVShows.DataModels;

namespace TVShows.Web.Controllers
{
    public class CharacterController : Controller
    {
        [HttpGet]
        public ActionResult AddCharacter(int id)
        {
            TVShow show;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                show = db.TVShows.Find(id);
            }
            return View(show);
        }
        [HttpPost]
        public ActionResult AddCharacter(string name, int id)
        {
            Character c = new Character();
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                c.Name = name;
                c.TVShowId = id;
                c = db.Characters.Add(c);
                db.SaveChanges();
            }
            return Redirect("/TVShow/Details/" + c.TVShowId);
        }
        public ActionResult Details(int id)
        {
            Character c;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                c = db.Characters.Where(x => x.Id == id).FirstOrDefault();
            }
            return View(c);
        }
        [HttpGet]
        public ActionResult EditCharacter(int id)
        {
            Character c;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                c = db.Characters.Where(x => x.Id == id).FirstOrDefault();
            }
            return View(c);
        }

        [HttpPost]
        public ActionResult EditCharacter(string name, int id)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Character c = db.Characters.Find(id);
                c.Name = name;
                db.SaveChanges();
            }
            return RedirectToAction("Details/"+id);
        }

        public ActionResult DeleteCharacter(int id)
        {
            int redirectID;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Character c = db.Characters.Find(id);
                redirectID = c.TVShowId;
                db.Characters.Remove(c);
                db.SaveChanges();
            }
            return Redirect("/TVShow/Details/"+ redirectID);
        }
	}
}